package com.ophelisis.common.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Vector;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.DurationFormatUtils;

@SuppressWarnings("unchecked")
public class DateUtil extends DateUtils{
	
	/**
	 * <pre>
	 * Method : DateUtil.now()
	 * 	현재 시각을 Date 형식으로 가져온다.
	 * <br>
	 * 	return type of Date
	 * <br>
	 * @return
	 * </pre>
	 */
	public static Date now() {
		return Calendar.getInstance().getTime();
	}	
	public static long nowMili() {
		return System.currentTimeMillis();
	}	

	/** 날짜 중간에 삽입된 기호들을 제거한다. */
	public static String trim(String str) {
		if(str==null) return null;
		return str.trim().replaceAll("[-/\\. :]", "");
	}

	/**
	 * 날짜 포맷
	 * getFmtDateTime("20070901")	=> 2007-09-01
	 * getFmtDateTime("20070901121212")	=> 2007-09-01 12:12:12
	 */
    public static String getFmtDateTime(String str) {
    	return getFmtDateTime(str, str==null ? 0 : str.length());
    }

    /**
	 * 날짜 포맷
	 * sep :  년월일 별로 구분하기 위한 특수문자 입력
	 * getFmtDateTime("20070901", "-")	=> 2007-09-01
	 * getFmtDateTime("20070901", ".")	=> 2007.09.01
	 */
    public static String getFmtDateTime(String str, String sep) {
    	return getFmtDateTime(str, sep, str.length());
    }

	/**
	 * 날짜 포맷
	 * outType : 출력형태
	 * getFmtDateTime("20070901121212", 8)	=> 2007-09-01
	 */
    public static String getFmtDateTime(String str, int outType) {
    	return getFmtDateTime(str, "-", str==null ? 0 : outType);
    }

	/**
	 * 날짜 포맷
	 * sep :  년월일 별로 구분하기 위한 특수문자 입력
	 * outType : 출력형태
	 * getFmtDateTime("20070901121212", 8)	=> 2007-09-01
	 */
    public static String getFmtDateTime(String str, String sep, int outType) {
    	String ret = "";

    	if(StringUtil.isEmpty(sep)) sep = "";
    	if(str==null || "".equals(str.trim())) return ret;
    	if(outType==0) outType = str.length();
    	if(str.length()==4) str += "0101";
    	if(str.length()==6) str += "01";
   		Date date = ymdToDate(StringUtil.rpad(str, 14, "0"), "yyyyMMddHHmmss");

    	return getFmtDateTime(date, sep, outType);
    }

    public static String getFmtDateTime(Date date, int outType) {
    	return getFmtDateTime(date, "", outType);
    }
    public static String getFmtDateTime(Date date, String sep, int outType) {
    	String ret = "";
    	if(date==null) return ret;
    	if(sep==null) sep = "";

    	switch(outType) {
			case   4:	ret = dateToYmd(date,	"yyyy"); 								break;
			case   6:	ret = dateToYmd(date,	"yyyy"+sep+"MM");  						break;
			case   8:	ret = dateToYmd(date,	"yyyy"+sep+"MM"+sep+"dd");  			break;
			case  10:	ret = dateToYmd(date,	"yyyy"+sep+"MM"+sep+"dd HH");  			break;
			case  12:	ret = dateToYmd(date,	"yyyy"+sep+"MM"+sep+"dd HH:mm");  		break;
			case  14:	ret = dateToYmd(date,	"yyyy"+sep+"MM"+sep+"dd HH:mm:ss");		break;
			case  16:  ret = dateToYmd(date, 	"yyyy"+sep+"MM"+sep+"dd a HH:mm:ss");	break;
			case 104:	ret = dateToYmd(date,	"yyyy년"); 								break;
			case 106:	ret = dateToYmd(date,	"yyyy년 M월");  						break;
			case 108:	ret = dateToYmd(date,	"yyyy년 M월 d일");  					break;
			case 110:	ret = dateToYmd(date,	"yyyy년 M월 d일 H시");  				break;
			case 111:	ret = dateToYmd(date,	"yyyy년 M월 d일 a h시");  				break;
			case 112:	ret = dateToYmd(date,	"yyyy년 M월 d일 H시 m분");  			break;
			case 113:	ret = dateToYmd(date,	"yyyy년 M월 d일 a h시 m분");  			break;
			case 114:	ret = dateToYmd(date,	"yyyy년 M월 d일 H시 m분 s초");  			break;
			case 115:	ret = dateToYmd(date,	"yyyy년 M월 d일 a h시 m분 s초");  		break;
			case 214:	ret = dateToYmd(date,	"yyyy년 M월 d일  HH:mm:ss");  			break;
			case 314:	ret = dateToYmd(date,	"yyyyMMddHHmmss");		break;
			default:	throw new IllegalArgumentException("표시할 수 없는 출력 포맷입니다.");
    	}
    	return ret;
    }

	// 날짜 관련 Start ***************************************************//
	public static String dateToYmd(Date date, String formatOut) {
		String strOut = null;
		SimpleDateFormat formatter = null;
		try {
			formatter = new SimpleDateFormat(formatOut, Locale.KOREA);
			strOut = formatter.format(date);
		} catch (Exception e) {
			return strOut;
		}
		return strOut;
	}

	public static Date ymdToDate(String strIn, String formatIn, Locale locale) {
		Date date = null;
		SimpleDateFormat formatter = null;
		try {
			formatter = new SimpleDateFormat(formatIn, locale);
			date = formatter.parse(strIn);
		} catch (Exception e) {
			return date;
		}
		return date;
	}

	public static Date ymdToDate(String strIn, String formatIn) {
		return ymdToDate(strIn, formatIn, Locale.KOREA);
	}

	// ymdToYmd("20070704131610", "yyyyMMddHHmmss", "yyyy-MM-dd a hh:mm")
	public static String ymdToYmd(String strIn, String formatIn,
			String formatOut) {
		Date date = ymdToDate(strIn, formatIn);
		return date == null ? "" : dateToYmd(date, formatOut);
	}
	// 날짜 관련 End ***************************************************//

	/**
	 * <pre>
	 * Method : DateUtil.getFmtUptime()
	 * 	uptime is seconds, getFmtUptime | 360000.21875 Sec ==>4d 4h 0m 0.218s
	 * <br>
	 * 	return type of String
	 * <br>
	 * @param uptime
	 * @return 
	 * </pre>
	 */
	public static String getFmtUptimeMiliseconds(double uptime) {
	    
		//return getFmtUptime(uptime, "d", "h", "m");
		return getFmtUptime(uptime, "d ", "h ", "m ", ".", "s");
	}
	public static String getFmtUptimeMiliseconds(String uptime) {
	    double uptimeVal = 0;
		if (uptime==null) return "-";
		try {
			uptimeVal=(double)Double.parseDouble(uptime);
		} catch(Exception e) {}
		//if (uptimeVal==0) return "-";
		
		return getFmtUptimeMiliseconds((double)(uptimeVal/1000));
	}
	public static String getFmtUptime(double uptime) {
	    
		return getFmtUptime(uptime, "d", "h", "m");
	}
	public static String getFmtUptimeMiliseconds(String startdate, String enddate) {
		double uptimemiliseconds = getBetweenDateTime(startdate, enddate);
		return getFmtUptimeMiliseconds((uptimemiliseconds/1000));
	}
	public static String getFmtUptimeMiliseconds(Date startdate, Date enddate) {
		 
		double uptimemiliseconds = getBetweenDateTime(startdate, enddate);
		return getFmtUptimeMiliseconds((uptimemiliseconds/1000));
	}

	// uptime is seconds
	public static String getFmtUptime(String uptime, String strDay,
			String strHour, String strMin) {
		try {
			return getFmtUptime(Double.parseDouble(uptime), strDay, strHour,
					strMin);
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * <pre>
	 * Method : DateUtil.getFmtDuration()
	 * 	time is miliSeconds, getFmtDuration | 360000.21875 Sec ==>100:0:0.218
	 * <br>
	 * 	return type of String
	 * <br>
	 * @param time
	 * @param strHour
	 * @param strMin
	 * @param strSec
	 * @return 
	 * </pre>
	 */
	public static String getFmtDuration(double time, String strHour,
			String strMin, String strSec) {
		return getFmtDuration((long) time, strHour, strMin, strSec);
	}

	/**
	 * <pre>
	 * Method : DateUtil.getFmtDuration()
	 * 	time is miliSeconds
	 * <br>
	 * 	return type of String
	 * <br>
	 * @param time
	 * @param strHour
	 * @param strMin
	 * @param strSec
	 * @return 
	 * </pre>
	 */
	public static String getFmtDuration(long time, String strHour,
			String strMin, String strSec) {
		String format = "H" + strHour + "m" + strMin + "s" + strSec + "S";
		return getFmtDuration(time, format);
	}

	/**
	 * <pre>
	 * Method : DateUtil.getFmtDuration()
	 * 	time is miliSeconds
	 * <br>
	 * 	return type of String
	 * <br>
	 * @param time
	 * @param format
	 * @return 
	 * </pre>
	 */
	public static String getFmtDuration(double time, String format) {
		return getFmtDuration((long) time, format);
	}

	/**
	 * <pre>
	 * Method : DateUtil.getFmtDuration()
	 * 	time is miliSeconds
	 * <br>
	 * 	return type of String
	 * <br>
	 * @param time
	 * @param format
	 * @return 
	 * </pre>
	 */
	public static String getFmtDuration(long time, String format) {
		return DurationFormatUtils.formatDuration(time, format, true);
	}

	// FIXME::// uptime is miliseconds
	public static String getFmtUptime2(String uptime, String strDay,
			String strHour, String strMin) {
		try {
			return getFmtUptime(Double.parseDouble(uptime) / 1000d, strDay,
					strHour, strMin);
		} catch (Exception e) {
		}
		return null;
	}
	/**
	 * <pre>
	 * Method : DateUtil.getFmtUptime()
	 * 	uptime is seconds
	 * <br>
	 * 	return type of String
	 * <br>
	 * @param uptime
	 * @param strDay
	 * @param strHour
	 * @param strMin
	 * @return 
	 * </pre>
	 */
	public static String getFmtUptime(double uptime, String strDay,
			String strHour, String strMin) {
		String retval = "";

		int days = (int) uptime / (60 * 60 * 24);
		int minutes, hours;

		if (days != 0) {
			retval += days + ((days > 1) ? strDay : strDay);
		}

		minutes = (int) uptime / 60;
		hours = minutes / 60;
		hours %= 24;
		minutes %= 60;

		if (hours != 0) {
			retval += hours + strHour + minutes + strMin;
		} else {
			retval += minutes + strMin;
		}

		return retval;
	}

	/**
	 * <pre>
	 * Method : DateUtil.getFmtUptime()
	 * 	uptime is seconds, getFmtUptime | 360000.21875 Sec ==>4d 4h 0m 0.218s
	 * <br>
	 * 	return type of String
	 * <br>
	 * @param uptime
	 * @param strDay
	 * @param strHour
	 * @param strMin
	 * @param strSec
	 * @param strMili
	 * @return 
	 * </pre>
	 */
	public static String getFmtUptime(double uptime, String strDay,
		String strHour, String strMin, String strSec, String strMili) {
    	String retval = "";
    
    	int days = (int) uptime / (60 * 60 * 24);
    	int minutes, hours;
    	int milis, seconds;
    
    	if (days != 0) {
    		retval += days + ((days > 1) ? strDay : strDay);
    	}
    
    	minutes = (int) uptime / 60;
    	hours = minutes / 60;
    	hours %= 24;
    	minutes %= 60;
    
    	seconds = (int) uptime % 60;
    	milis = (int)((uptime - (int) uptime)*1000);
    	
    	if (hours != 0) {
    		retval += hours + strHour + minutes + strMin + seconds + strSec + milis + strMili;
    	} else {
    	    	if (minutes != 0) {
    	    	    	retval += minutes + strMin + seconds + strSec + milis + strMili;
    	    	} else {
    	    	    	retval += seconds + strSec + milis + strMili;
    	    	}
    	}

    	return retval;
    }	
	
    /**
     * 날짜 포맷
     * getSplitDate("2007-09-01")	=> 20070901
     *
     */
    public static String getSplitDate(String yyyymmdd) {
		String ymd = yyyymmdd.trim();
		if (ymd.length() == 7)
			return ymd.substring(0, 4)
				+ ymd.substring(5, 7);
		else if (ymd.length() == 10)
			return ymd.substring(0, 4)
				+ ymd.substring(5, 7)
				+ ymd.substring(8, 10);
		else
			return ymd;
	}


    /** 현재 시간이 from, to 에 포함되는지 여부
	 *  예)입력형태 20070901220103, 200709012 등..
     */
    public static boolean isBetweenCurrDate(String from, String to) {
    	Date currDate = new Date();
		return currDate.compareTo(parseDate(from))>=0 && currDate.compareTo(parseDate(to))<=0;
	}

    /** 두 시간의 차이를 구한다. */
	public static long getBetweenDateTime(String from, String to) {
		return getBetweenDateTime(parseDate(from), parseDate(to));
	}

    /** 두 시간의 차이를 구한다. */
	public static long getBetweenDateTime(Date from, Date to) {
		return to.getTime() - from.getTime();
	}

	/** 두 시간의 차이를 구한다. (날짜) */
	public static int getBetweenDays(String from, String to) {
//		return Integer.parseInt(to.substring(0, 8)) - Integer.parseInt(from.substring(0, 8));
		long gap = getBetweenDateTime(from, to);
//		long time = 1000; 	//1초
//		time *= 60;			//1분
//		time *= 60;			//1시간
//		time *= 24;			//1일
		long time = 86400000;
		return (int)(gap / time);
	}

	/** 입력문자열을 Date객체로 리턴한다.
	 *  날짜입력형태 20070901220103, 200709012 등..
	 */
	public static Date parseDate(String str) {
		
		String dateStr = trim(str);
		//System.out.println("str len="+str.length() + " dateStr len=" + dateStr.length());
		if (dateStr.length() > 14) 
			return ymdToDate(StringUtil.rpad(dateStr, 17, "0"), "yyyyMMddHHmmssSSS");
		
		return ymdToDate(StringUtil.rpad(dateStr, 14, "0"), "yyyyMMddHHmmss");
	}

	/** 윤년여부 */
	public static boolean isLeapYear(String str) {
		return new GregorianCalendar().isLeapYear(Integer.parseInt(str.substring(0,4)));
	}

	/** 정상적인 날짜여부 */
	public static boolean isValidDate(String str) {
		str = StringUtil.rpad(str, 14, "0");
		return str.equals(dateToYmd(parseDate(str), "yyyyMMddHHmmss"));
	}

	/**
	 *
	 * @param sDate 날짜 to
	 * @param eDate 날짜 From
	 * @param iFlag 1:일일 기준, 2:월 기준, "": 년기준
	 * @param iDel  년+"iDel"+월+"iDel"+일
	 * @return
	 */
	 @SuppressWarnings("rawtypes")
	public static Vector getDates(String sDate, String eDate, String iFlag, String iDel) {
		Vector vDates = new Vector();

		int sYYYY = Integer.parseInt(sDate.substring(0, 4));
		int sMM = Integer.parseInt(sDate.substring(4, 6));
		int sDD = Integer.parseInt(sDate.substring(6, 8));

		int eYYYY = Integer.parseInt(eDate.substring(0, 4));
		int eMM = Integer.parseInt(eDate.substring(4, 6));
		int eDD = Integer.parseInt(eDate.substring(6, 8));

		Calendar startNow = Calendar.getInstance();
		startNow.set(sYYYY, sMM - 1, sDD);

		Calendar endNow = Calendar.getInstance();
		endNow.set(eYYYY, eMM - 1, eDD);


		long lST = startNow.getTime().getTime();
		long lET = endNow.getTime().getTime();
		long oneDay = (1000L * 60 * 60 * 24);


		if (iFlag.equals("1")) {
			for (long i = lST; i <= lET; i += oneDay, startNow.add(Calendar.DATE, 1)) {
			vDates.addElement(startNow.get(Calendar.YEAR) + iDel +
				(startNow.get(Calendar.MONTH) + 1 < 10 ? "0" + (startNow.get(Calendar.MONTH) + 1) : "" + (startNow.get(Calendar.MONTH) + 1)) + iDel +
				(startNow.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + startNow.get(Calendar.DAY_OF_MONTH) : "" + startNow.get(Calendar.DAY_OF_MONTH)));
			}

		} else if (iFlag.equals("2")) {
			for (int i = sYYYY; i <= eYYYY; i++) {
			for (int j = (i == sYYYY ? sMM : 1); j <= (i < eYYYY ? 12 : eMM); j++) {
				vDates.addElement(i + iDel + (j < 10 ? "0" + j : "" + j) + iDel + "01");
			}
			}
		} else {
			for (int i = sYYYY; i <= eYYYY; i++) {
			vDates.addElement(i + iDel + "01" + iDel + "01");
			}

		}
		return (vDates);
	}

    /**
     * 현재의 날짜를 포멧에 맞게 변환 해준다.(한글포멧)
     *
     * @param format
     * @return
     */
    public static String getCurrentDate(String format)
    {
        return  getCurrentDate(format, Locale.KOREA);
    }

    /**
     * 현재의 날짜를 포멧에 맞게 변환 해준다.
     * <pre>
     * SimpleDateFormat Format Syntax
     * G        era designator          (Text)              AD
     * y        year                    (Number)            1996
     * M        month in year           (Text & Number)     July & 07
     * d        day in month            (Number)            10
     * h        hour in am/pm (1~12)    (Number)            12
     * H        hour in day (0~23)      (Number)            0
     * m        minute in hour          (Number)            30
     * s        second in minute        (Number)            55
     * S        millisecond             (Number)            978
     * E        day in week             (Text)              Tuesday
     * D        day in year             (Number)            189
     * F        day of week in month    (Number)            2 (2nd Wed in July)
     * w        week in year            (Number)            27
     * W        week in month           (Number)            2
     * a        am/pm marker            (Text)              PM
     * k        hour in day (1~24)      (Number)            24
     * K        hour in am/pm (0~11)    (Number)            0
     * z        time zone               (Text)              Pacific Standard Time
     * '        escape for text         (Delimiter)
     * ''       single quote            (Literal)           '
     * </pre>
     * 예) WUtil.getCurrentDate("yyyy년 MM월 dd일")
     * WUtil.getSvcLang("KR", WUtil.getCurrentDate("yyyy년 MM월 dd일"), WUtil.getCurrentDate("MM dd, yyyy"))
     * WUtil.getCurrentFullDate("KR")
     *
     * @param format
     * @param loc
     * @return
     */
    public static String getCurrentDate(String format, Locale loc)
    {
        if (format == null || format.equals("")) return "";

        SimpleDateFormat formatter = new SimpleDateFormat(format, loc);
        return formatter.format(new Date());
    }


    /*
     * fromDate - toDate
     */
    public static final int getDateGap(String toDate, String fromDate, String format) {
        //long MpSec = 1000;
        //long MpMin = 60*1000;
        //long MpHou = 60*60*1000;
        long MpDay = 24*60*60*1000;

        try {
        	SimpleDateFormat formatter = new SimpleDateFormat(format);
        	Date to_Date = ((DateFormat)formatter).parse(toDate);
        	Date from_Date = ((DateFormat)formatter).parse(fromDate);

        	Calendar before = new GregorianCalendar();
            Calendar after  = new GregorianCalendar();

            before.setTime(to_Date);
            after.setTime(from_Date);

            long millis = after.getTime().getTime()-before.getTime().getTime();
            long days = millis / MpDay;
            //long hours = millis / MpHou;
            //long minutes = millis / MpMin;
            //long seconds = millis / MpSec;
            //logger.debug("밀리초차이:"+millis);
            //logger.debug("초차이:"+seconds);
            //logger.debug("분차이:"+minutes);
            //logger.debug("시간차이:"+hours);
            /*
            logger.debug("날차이:"+days);
            logger.debug(days+"일 "
                              +(millis%MpDay)/MpHou+"시간 "
                              +((millis%MpDay)%MpHou)/MpMin+"분 "
                              +(((millis%MpDay)%MpHou)%MpMin)/MpSec+"초 차이");
            */
            return (int)days;
        } catch (Exception e) {
        	return 0;
        }
    }

    public static final int getDateGap(String toDate, String fromDate, String format, String type) {
        long MpSec = 1000;
        long MpMin = 60*1000;
        long MpHou = 60*60*1000;
        long MpDay = 24*60*60*1000;

        try {
        	SimpleDateFormat formatter = new SimpleDateFormat(format);
        	Date to_Date = ((DateFormat)formatter).parse(toDate);
        	Date from_Date = ((DateFormat)formatter).parse(fromDate);

        	Calendar before = new GregorianCalendar();
            Calendar after  = new GregorianCalendar();

            before.setTime(to_Date);
            after.setTime(from_Date);

            long millis = after.getTime().getTime()-before.getTime().getTime();
            long days = millis / MpDay;
            long hours = millis / MpHou;
            long minutes = millis / MpMin;
            long seconds = millis / MpSec;
            //long hours = millis / MpHou;
            //long minutes = millis / MpMin;
            //long seconds = millis / MpSec;
            //logger.debug("밀리초차이:"+millis);
            //logger.debug("초차이:"+seconds);
            //logger.debug("분차이:"+minutes);
            //logger.debug("시간차이:"+hours);
            /*
            logger.debug("날차이:"+days);
            logger.debug(days+"일 "
                              +(millis%MpDay)/MpHou+"시간 "
                              +((millis%MpDay)%MpHou)/MpMin+"분 "
                              +(((millis%MpDay)%MpHou)%MpMin)/MpSec+"초 차이");
            */
            if ( type.equals("DAY") ) return (int)days;
            if ( type.equals("HOUR") ) return (int)hours;
           	if ( type.equals("MINUTE") ) return (int)minutes;
           	if ( type.equals("SECOND") ) return (int)seconds;
           	else return (int)days;
        } catch (Exception e) {
        	return 0;
        }
    }

	 /**
     * <PRE>
     * milli second의 값을 입력받은 format의 스트링으로 리턴한다..
     * format에 대한 내용은 java.text.SimpleDateFormat class의 api를 참조.
     * 사용예)
     * String time = "1119410042";
	 * logger.debug("time = " + DateUtil.getDate(Long.parseLong(time) * 1000, "yyyyMMddHHmmss"));
	 * String millSecond = "1121925709715";
	 * logger.debug("time = " + DateUtil.getDate(Long.parseLong(millSecond), "yyyyMMddHHmmssS"));
     * @param milliSecond
     * @param format
     * @return
     * </PRE>
     */
    public static final String getDate(long milliSecond, String format) {
        SimpleDateFormat dateFormat = null;
        Date date = null;
        String currDate = null;
    	try {
    		dateFormat = new SimpleDateFormat(format);
    		date = new Date(milliSecond);
    		currDate = dateFormat.format(date);
        } catch(Exception e) {
        	e.printStackTrace();
        } finally {
        	dateFormat = null;
            date = null;
            format = null;
        }
        return currDate;
    }

	/**
	 * 1970년 01월 01일 부터의 Seconds 반환.
	 * @param dateStr
	 * @param format
	 * @return
	 */
	public static long getSecondsFrom1970(String dateStr, String format) {
		long resVal = 0;
		SimpleDateFormat dateFormat = new SimpleDateFormat(format) ;

		try {
			Date date = ((DateFormat)dateFormat).parse(dateStr) ;
			Calendar calendar = Calendar.getInstance() ;
			calendar.setTime(date) ;
			resVal= calendar.getTimeInMillis()/1000 ;
		}
		catch(Exception e) {
			e.printStackTrace() ;
		}
		return resVal ;
	}
	
	public static String timeToDHM(long duration
			, String strDay, String shour, String smin, String ssec) {
		long temp = duration / (1000 * 60 * 60 * 24);
		String res = temp + strDay;
		duration -= temp * (1000 * 60 * 60 * 24);
		temp = duration / (1000 * 60 * 60);
		res += temp + " hours and ";
		duration -= temp * (1000 * 60 * 60);
		temp = duration / (1000 * 60);
		res += temp + " minutes";
		duration -= temp * (1000 * 60);
		temp = duration / (1000);
		res += temp + " sec";
		return res;
	}

	/*****************************************
	 * 현재 시각 획득 
	 */
	public static Date nowDate() {
		return now();
	}
	public static String nowDateString() {
		return getCurrentDate("yyyy-MM-dd HH:mm:ss.SSS");
	}
	public static String nowDateString(String formatOut) {
		return getCurrentDate(formatOut);
	}
	public static long nowDateLong() {
		return now().getTime();
	}
	public static Date nowDate(String type, int gap) {
		Calendar cal = Calendar.getInstance();
		DateUtil.addCalDate(cal, type, gap);
		
		return cal.getTime();
	}
	public static String nowDateString(String type, int gap) {
		Calendar cal = Calendar.getInstance();
		DateUtil.addCalDate(cal, type, gap);
		
		return DateUtil.dateToYmd(cal.getTime(),"yyyy-MM-dd HH:mm:ss.SSS");
	}
	public static String nowDateString(String type, int gap, String formatOut) {
		Calendar cal = Calendar.getInstance();
		DateUtil.addCalDate(cal, type, gap);
		
		return DateUtil.dateToYmd(cal.getTime(),formatOut);
	}
	@SuppressWarnings("static-access")
	public static Calendar addCalDate(Calendar cal, String type, int gap) {
		if (type.equals("YEAR") || type.equals("year")) {
			cal.add(cal.YEAR, gap);
		} else if (type.equals("MONTH") || type.equals("month")) {
			cal.add(cal.MONTH, gap);
		} else if (type.equals("DAY") || type.equals("day")) {
			cal.add(cal.DAY_OF_MONTH, gap);
		} else if (type.equals("HOUR") || type.equals("hour")) {
			cal.add(cal.HOUR_OF_DAY, gap);
		} else if (type.equals("MINUTE") || type.equals("minute")) {
			cal.add(cal.MINUTE, gap);
		} else if (type.equals("SECOND") || type.equals("second")) {
			cal.add(cal.SECOND, gap);
		} else if (type.equals("MILLISECOND") || type.equals("millisecond")) {
			cal.add(cal.MILLISECOND, gap);
		}
		return cal;
	}
	
	/*****************************************
	 * 시각 변환 
	 */
	public static String convStringFromMiliseconds(long milliSecond, String formatOut) {
		return getDate(milliSecond, formatOut);
	}
	public static String convStringFromSeconds(long second, String formatOut) {
		return getDate((second*1000), formatOut);
	}
	public static String convStringFromDate(Date date, String formatOut) {
		return dateToYmd(date, formatOut);
	}
	public static long convMilisecondsFromString(String datetime) {
		return parseDate(datetime).getTime();
	}
	public static long convMilisecondsFromDate(Date date) {
		return date.getTime();
	}
	public static long convSecondsFromString(String datetime) {
		return (parseDate(datetime).getTime()/1000);
	}
	public static long convSecondsFromDate(Date date) {
		return (date.getTime()/1000);
	}
	public static Date convDateFromString(String datetime) {
		return parseDate(datetime);
	}
	public static Date convDateFromMiliseconds(long milliSecond) {
		return new Date(milliSecond);
	}
	
	/*****************************************
	 * 지속 시간 변환 
	 */
	public static void main(String[] args) {
		//System.out.println(getFmtDuration(1199800, "H시 m분 s초"));

		
		// 초기 값 생성 (Date, String, long)
		Date std = DateUtil.now();
		String stdStr = DateUtil.dateToYmd(std, "yyyy-MM-dd HH:mm:ss.SSS");
		long stdl = std.getTime();
		
		System.out.println("Current std {now()}="+std);
		System.out.println("Current stdStr {now()}="+stdStr);
		System.out.println("Current stdl {now()}="+stdl);
		
		String st = DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss.SSS");
		System.out.println("Current st {yyyy-MM-dd HH:mm:ss.SSS}="+st);

		String st1 = DateUtil.getCurrentDate(ConstUtil.LOG_DATE_FORMAT);
		System.out.println("Current st {"+ConstUtil.LOG_DATE_FORMAT+"}="+st1);

		
		
		try {
			Thread.sleep(2300);
		} catch (InterruptedException e) {
			System.out.println("InterruptedException :: " + e.getCause() + " :: " + e.getMessage());
			e.printStackTrace();
		}
		Date edd = DateUtil.now();
		String eddStr = DateUtil.dateToYmd(edd, "yyyy-MM-dd HH:mm:ss.SSS");
		long eddl = edd.getTime();

		System.out.println("Current edd {now()}="+edd);
		System.out.println("Current eddStr {now()}="+eddStr);
		System.out.println("Current eddl {now()}="+eddl);
		
		String ed = DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss.SSS");
		System.out.println("Current ed {yyyy-MM-dd HH:mm:ss.SSS}="+ed);

		System.out.println("");
		
		long durl = eddl - stdl;
		System.out.println("long stdl{"+stdl+"}"+" eddl{"+eddl+"}"+" durl{"+durl+"}");
		
		double dur = DateUtil.getBetweenDateTime(std, edd);
		
		Date stDate = DateUtil.parseDate(st);
		Date edDate = DateUtil.parseDate(ed);
		System.out.println("Date stDate{"+stDate+"}"+" edDate{"+edDate+"}");
		
		double dur4str = DateUtil.getBetweenDateTime(st, ed);
		double dur4datestr = DateUtil.getBetweenDateTime(stdStr, eddStr);
		//double dur = DateUtil.getBetweenDateTime(st, ed);
		String gab = DateUtil.getFmtUptimeMiliseconds((double)(dur/1000));
		String gab4datestr = DateUtil.getFmtUptimeMiliseconds((double)(dur4datestr/1000));
		String gab4str = DateUtil.getFmtUptimeMiliseconds((double)(dur4str/1000));
		System.out.println("using Date :: duration ="+dur + " gab ="+gab);
		System.out.println("using DateString :: duration ="+dur4datestr + " gab ="+gab4datestr);
		System.out.println("using String :: duration ="+dur4str + " gab ="+gab4str);

		System.out.println("using Date :: "+getFmtUptimeMiliseconds(std, edd));
		System.out.println("using DateString :: "+getFmtUptimeMiliseconds(stdStr, eddStr));
		
		
		
		@SuppressWarnings("unused")
		String bootTime="2013.1.9 6:14:51.79";
		
	}

	
	public static String getDate(String check)
    {
        Date date = new Date();
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat datetime = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        SimpleDateFormat yyyy = new SimpleDateFormat("yyyy");
        SimpleDateFormat yy = new SimpleDateFormat("yy");
        SimpleDateFormat mm = new SimpleDateFormat("MM");
        SimpleDateFormat dd = new SimpleDateFormat("dd");
        SimpleDateFormat HH = new SimpleDateFormat("HH");
        SimpleDateFormat mi = new SimpleDateFormat("mm");
        SimpleDateFormat ss = new SimpleDateFormat("ss");
        SimpleDateFormat ms = new SimpleDateFormat("SSS");
        String strdate = simpleDate.format(date);
        String strdatetime = datetime.format(date);
        String lYear = yyyy.format(date);
        String sYear = yy.format(date);
        String month = mm.format(date);
        String day = dd.format(date);
        String hour = HH.format(date);
        String minute = mi.format(date);
        String second = ss.format(date);
        String milisecond = ms.format(date);
        if(check.equals("yyyy"))
            return lYear;
        if(check.equals("yy"))
            return sYear;
        if(check.equals("mm"))
            return month;
        if(check.equals("dd"))
            return day;
        if(check.equals("hh"))
            return hour;
        if(check.equals("mi"))
            return minute;
        if(check.equals("ss"))
            return second;
        if(check.equals("ms"))
            return milisecond;
        if(check.equals("date"))
            return strdate;
        if(check.equals("yyyymmdd"))
            return (new StringBuilder(String.valueOf(lYear))).append(month).append(day).toString();
        if(check.equals("yyyymm"))
            return (new StringBuilder(String.valueOf(lYear))).append(month).toString();
        if(check.equals("yymmdd"))
            return (new StringBuilder(String.valueOf(sYear))).append(month).append(day).toString();
        if(check.equals("yymm"))
            return (new StringBuilder(String.valueOf(sYear))).append(month).toString();
        if(check.equals("hhmiss"))
            return (new StringBuilder(String.valueOf(hour))).append(minute).append(second).toString();
        if(check.equals("datetime"))
            return strdatetime;
        if(check.equals("hhmissms"))
            return (new StringBuilder(String.valueOf(hour))).append(":").append(minute).append(":").append(second).append(":").append(milisecond).toString();
        if(check.equals("total"))
            return (new StringBuilder(String.valueOf(lYear))).append(month).append(day).append(hour).append(minute).append(second).append(milisecond).toString();
        else
            return "";
    }

    public static String getDate(long millis)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millis);
        int yy = cal.get(1);
        int mm = cal.get(2) + 1;
        int dd = cal.get(5);
        StringBuffer sDate = new StringBuffer();
        sDate.append(yy);
        if(mm < 10)
            sDate.append("0").append(mm);
        else
            sDate.append(mm);
        if(dd < 10)
            sDate.append("0").append(dd);
        else
            sDate.append(dd);
        return sDate.toString();
    }
	
	public static String getFullDate(String gubun)
    {
        return (new StringBuilder(String.valueOf(getDate("yyyy")))).append(gubun).append(getDate("mm")).append(gubun).append(getDate("dd")).toString();
    }
	
	public static String getFullTime(String gubun)
    {
        return (new StringBuilder(String.valueOf(getDate("hh")))).append(gubun).append(getDate("mi")).append(gubun).append(getDate("ss")).toString();
    }
	
	public static String getDatetime()
    {
        String temp = (new StringBuilder(String.valueOf(getDate()))).append(getTime()).toString();
        return temp;
    }
	
	public static String getDate()
    {
        Calendar cal = Calendar.getInstance();
        int yy = cal.get(1);
        int mm = cal.get(2) + 1;
        int dd = cal.get(5);
        StringBuffer sDate = new StringBuffer();
        sDate.append(yy);
        if(mm < 10)
            sDate.append("0").append(mm);
        else
            sDate.append(mm);
        if(dd < 10)
            sDate.append("0").append(dd);
        else
            sDate.append(dd);
        return sDate.toString();
    }
	
	public static String getTime()
    {
        Calendar cal = Calendar.getInstance();
        int hh = cal.get(11);
        int mm = cal.get(12);
        int ss = cal.get(13);
        int mili = cal.get(14);
        String hhh = null;
        String mmm = null;
        String sss = null;
        @SuppressWarnings("unused")
		String milis = null;
        if(hh < 10)
            hhh = (new StringBuilder("0")).append(hh).toString();
        else
            hhh = (new StringBuilder()).append(hh).toString();
        if(mm < 10)
            mmm = (new StringBuilder("0")).append(mm).toString();
        else
            mmm = (new StringBuilder()).append(mm).toString();
        if(ss < 10)
            sss = (new StringBuilder("0")).append(ss).toString();
        else
            sss = (new StringBuilder()).append(ss).toString();
        
        milis = (new StringBuilder()).append(mili).toString();
        
        String addTime = (new StringBuilder()).append(hhh).append(mmm).append(sss).toString();
        return addTime;
    }

	public static long getDateMilis(Calendar date) {
		  if (date==null) return 0;
	      return date.getTimeInMillis();
	  }
	
//	public static String getDateString(Calendar date) {
//		  if (date==null) return "n/a";
//	      return date.get(Calendar.YEAR)//+"년 "
//	              + "." + (date.get(Calendar.MONTH)+1)// + "월 "
//	              + "." + date.get(Calendar.DATE)// + "일"
//	              + " " + date.get(Calendar.HOUR)// + "시"
//	              + ":" + date.get(Calendar.MINUTE)// + "분"
//	              + ":" + date.get(Calendar.SECOND)// + "초"
//	              + "." + date.get(Calendar.MILLISECOND)// + "밀리"
//	              ;
//	  }
	
	public static String stringToDate(String strDate) {
		DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.ENGLISH);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.KOREA);
		String afterDate = null;
		try {
			Date date = dateFormat.parse(strDate);
			afterDate = sdf.format(date);
		} catch (Exception e){
			e.printStackTrace();
		}
		
		
		return afterDate;
	}
}
